package org.donhuan.rms.ui.model;

import java.util.List;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.model.IWorkbenchAdapter;

public class RmsContentprovider implements ITreeContentProvider {
	protected ITreeAndWorkbenchAdapter getAdapter(Object element) {
		ITreeAndWorkbenchAdapter adapter = null;
		if (adapter instanceof IAdaptable) {
			adapter = (ITreeAndWorkbenchAdapter) ((IAdaptable) element)
					.getAdapter(ITreeAndWorkbenchAdapter.class);
		}
		if (element != null && adapter == null) {
			adapter = (ITreeAndWorkbenchAdapter) Platform.getAdapterManager()
					.getAdapter(element, ITreeAndWorkbenchAdapter.class.getName());
		}
		return adapter;
	}

	public void dispose() {

	}

	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		viewer.refresh();
	}

	@SuppressWarnings("rawtypes")
	public Object[] getElements(Object inputElement) {
		if (inputElement instanceof List)
			return ((List) inputElement).toArray();
		return getChildren(inputElement);
	}

	public Object[] getChildren(Object parentElement) {
		if(parentElement instanceof String )return new Object[0];
		IWorkbenchAdapter adapter = getAdapter(parentElement);
		if (adapter.getChildren(parentElement) != null) {
			return adapter.getChildren(parentElement);
		}
		return new Object[0];
	}

	public Object getParent(Object element) {
		IWorkbenchAdapter adapter = getAdapter( element);
		if (adapter != null) {
			return adapter.getParent(element);
		}
		return null;
	}

	public boolean hasChildren(Object element) {
		if(element==null)return false;
		return getChildren(element).length > 0;
	}

}
